﻿using System;
using System.Windows.Input;
using Samurai.DAL;
using Samurai.Infrastructure;
using Samurai.MovieIndustry;
using System.ComponentModel;
using System.Windows.Threading;

namespace Samurai.Client.Commands
{
    public class CreateMovieCommand : ICommand
    {
        private static CreateMovieCommand _instance;
        public static CreateMovieCommand Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new CreateMovieCommand();
                return _instance;
            }
        }

        public Func<Movie, bool> MovieCreated { get; set; }

        public Action MovieCreationInterrupted { get; set; }
        public Func<int, bool> MovieCreationCompleted { get; set; }


        private CreateMovieCommand()
        {
            _movieCount = 0;
        }

        private int _movieCount;

        void BackgroundWorkerDoWork1(object sender, DoWorkEventArgs e)
        {
            var candidateMovies = (CandidateMovie[])e.Argument;

            try
            {
                foreach (var candidateMovie in candidateMovies)
                {
                    if (!Manager.Instance.Exists(candidateMovie.Path))
                    {
                        var movieData = new MovieDirector().Generate(candidateMovie);

                        if (movieData.Error != null && (movieData.Error == Constants.ErrorMovieCreation || movieData.Error == Constants.WebError))
                        {
                            _isError = true;
                            break;
                        }

                        Manager.Instance.AddMovie(movieData);

                        if (string.IsNullOrEmpty(movieData.Error))
                        {
                            _movieCount++;
                            if (MovieCreated != null)
                                MovieCreated(movieData);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FailedWorking(ex);
            }
        }

        void BackgroundWorkerRunWorkerCompleted1(
            object sender,
            RunWorkerCompletedEventArgs e)
        {
            if (_isError == false)
            {
                if(MovieCreationCompleted != null)
                    MovieCreationCompleted(_movieCount);
            }

            else
            {
                if (MovieCreationInterrupted != null)
                    MovieCreationInterrupted();
            }
        }

        private bool _isError;

        public void Execute(object parameter)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;

            var candidateMovies = Manager.Instance.GetCandidateMovies();

            var backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += BackgroundWorkerDoWork1;

            backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted1;

            backgroundWorker.RunWorkerAsync(candidateMovies);

        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;


        private Dispatcher _dispatcher;
        private void FailedWorking(Exception ex)
        {
            _dispatcher.BeginInvoke(new NotifyWorkerFailedDelegate(NotifyWorkerFailed), DispatcherPriority.Normal, ex);
        }


        public delegate void NotifyWorkerFailedDelegate(Exception ex);

        private void NotifyWorkerFailed(Exception ex)
        {
            throw ex;
        }
    }

}
